package com.mars.controller;

import com.fasterxml.jackson.annotation.JsonView;
import com.mars.dto.User;
import com.mars.dto.UserQueryCondition;
import com.mars.exception.UserNotExistException;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @author MARS
 * @date 2018/7/15
 */

@RestController
@RequestMapping("/user")
public class UserController {

    /**
     * 把用户的唯一标示给予spring social
     */
    //@Autowired
    //private ProviderSignInUtils providerSignInUtils;

    /**
     * 自定义用户注册逻辑
     * @param user
     */
    //@PostMapping("/regist")
    //public void regist(User user, HttpServletRequest request) {
    //    // 自定义用户注册逻辑
    //    // 从数据库中获取userID
    //    String userId = user.getUsername();
    //    // 绑定数据，将信息插入到spring social的数据表中
    //    providerSignInUtils.doPostSignUp(userId,new ServletWebRequest(request));
    //}

    /**
     * 通过 SecurityContextHolder 获取用户信息
     * @return
     */
    @GetMapping("/me")
    public Object getCurrentUser(@AuthenticationPrincipal UserDetails userDetails){
        // 方式一：
        //return SecurityContextHolder.getContext().getAuthentication();

        // 方式二：直接传入一个Authentication的参数，直接返回
        //return authenticatoin;

        // 方式三：添加注解 @AuthenticationPrincipal UserDetails userDetails
        return userDetails;


    }

    /**
     * 查询所有user信息
     * @param username
     * @return
     */
    @GetMapping("/query")
    @JsonView(User.UserSimpleView.class)
    @ApiOperation("查询用户信息")
    public List<User> query(@RequestParam(value = "username",required = false,defaultValue = "tom") String username) {
       // 获取模拟mvc框架的 请求参数值
        System.out.println(username);
        List<User> userList = new ArrayList<>();
        userList.add(new User());
        userList.add(new User());
        userList.add(new User());
        return userList;
    }

    /**
     * 查询所有user信息，有分页
     * @param queryCondition
     * @param pageable
     * @return
     */
    @GetMapping("/queryDTO")
    @JsonView(User.UserSimpleView.class)
    @ApiOperation("查询用户信息列表")
    public List<User> queryDTO(UserQueryCondition queryCondition, @PageableDefault(page = 1,size = 10,sort = "username,asc") Pageable pageable) {

        System.out.println(ReflectionToStringBuilder.toString(queryCondition, ToStringStyle.MULTI_LINE_STYLE));

        System.out.println(pageable.getPageSize());
        System.out.println(pageable.getPageNumber());
        System.out.println(pageable.getSort());

        List<User> userList = new ArrayList<>();
        userList.add(new User());
        userList.add(new User());
        userList.add(new User());
        return userList;
    }


    /**
     * 根据id获取用户信息
     * @param id
     * @return
     */
    @GetMapping("/{id:\\d+}")
    @JsonView(User.UserDetailView.class)
    public User getInfo(@PathVariable String id) {

        //throw new UserNotExistException(id);
        System.out.println("进行入GetInfo服务");
        User user = new User();
        user.setUsername("tom");
        return user;
    }

    /**
     * 创建用户信息:post请求
     * @param user
     * @param bindingResult
     * @return
     */
    @PostMapping("/create")
    public User create(@Valid @RequestBody User user, BindingResult bindingResult){
        // bindingResult.hasErrors()判断是否有没有错误
        if (bindingResult.hasErrors()) {
            bindingResult.getAllErrors().stream().forEach(error -> System.out.println(error.getDefaultMessage()));
        }
        System.out.println(user.getId());
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        System.out.println(user.getBirthday());
        user.setId("1");
        return user;

    }

    /**
     * 更新用户信息：put请求
     * @param user
     * @param bindingResult
     * @return
     */
    @PutMapping("/{id:\\d+}")
    public User update(@Valid @RequestBody User user, BindingResult bindingResult){

        if (bindingResult.hasErrors()) {
            bindingResult.getAllErrors().stream().forEach(error -> System.out.println(error.getDefaultMessage()));
        }

        // lambda表达式，转换为错误对象
        //if (bindingResult.hasErrors()) {
        //    bindingResult.getAllErrors().stream().forEach(resources -> {
        //        // 将error强转为FieldError对象
        //        FieldError fieldError = (FieldError)resources;
        //        // 获取错误字段，以及错误提示信息
        //        String msg = fieldError.getField() + "  " +  resources.getDefaultMessage();
        //        System.out.println(msg);
        //    });
        //}
        System.out.println(user.getId());
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        System.out.println(user.getBirthday());
        user.setId("1");
        return user;
    }

    /**
     * 删除id
     * @param id
     */
    @DeleteMapping("/{id:\\d+}")
    public void delete(@ApiParam("用户id") @PathVariable String id){
        System.out.println(id);
    }
}
